﻿using H.Pipes;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace StudentSynchronization.Daemon
{
    public class TPipeServer : IAsyncDisposable
    {
        private string PipeName { get; }
        private PipeServer<string> Server { get; }
        private ISet<string> Clients { get; } = new HashSet<string>();

        public TPipeServer()
        {
            PipeName = "asdaskdjsa@岳雨婷as123131";

            Server = new PipeServer<string>(PipeName);
            Server.ClientConnected += async (o, args) =>
            {
                Clients.Add(args.Connection.PipeName);
                UpdateClientList();

                AddLine($"{args.Connection.PipeName} connected!");

                try
                {
                    await args.Connection.WriteAsync("系统运行正常").ConfigureAwait(false);
                }
                catch (Exception exception)
                {
                    OnExceptionOccurred(exception);
                }
            };
            Server.ClientDisconnected += (o, args) =>
            {
                Clients.Remove(args.Connection.PipeName);
                UpdateClientList();

                AddLine($"{args.Connection.PipeName} disconnected!");
            };
            Server.MessageReceived += Server_MessageReceived; ;
            Server.ExceptionOccurred += (o, args) => OnExceptionOccurred(args.Exception);
            OnLoad();
        }

        private void Server_MessageReceived(object sender, H.Pipes.Args.ConnectionMessageEventArgs<string> args)
        {
            if (args.Message.Contains("检测到更新"))
            {
                var path = args.Message.Replace("检测到更新", "");
                if (Directory.Exists(path))
                {
                    UpdateControl.Run(path);
                }
            }
            AddLine($"{args.Connection.PipeName}: {args.Message}");
        }

        private async void OnLoad()
        {

            try
            {
                AddLine("Server starting...");

                await Server.StartAsync().ConfigureAwait(false);

                AddLine("Server is started!");
            }
            catch (Exception exception)
            {
                OnExceptionOccurred(exception);
            }
        }

        private void OnExceptionOccurred(Exception exception)
        {
            AddLine($"Exception: {exception}");
        }

        private void AddLine(string text)
        {
            // 获取当前程序的基础目录
            string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;

            // 创建日志文件夹的路径
            string logDirectory = Path.Combine(baseDirectory, "Logs");

            // 如果日志文件夹不存在，则创建它
            if (!Directory.Exists(logDirectory))
            {
                Directory.CreateDirectory(logDirectory);
            }

            // 获取当前日期，用于生成日志文件名（格式：yyyyMMdd）
            string logFileName = DateTime.Now.ToString("yyyyMMdd") + ".txt";

            // 创建日志文件的完整路径
            string logFilePath = Path.Combine(logDirectory, logFileName);

            // 要追加的日志文本
            string logText = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + text + "\r\n";

            // 将日志文本追加到日志文件中
            try
            {
                File.AppendAllText(logFilePath, logText);
            }
            catch (Exception ex)
            {
            }



        }

        private void UpdateClientList()
        {

        }

        public async void SendMessage(string Text)
        {
            if (Server == null || string.IsNullOrWhiteSpace(Text))
            {
                return;
            }
            try
            {
                AddLine($"Sent to {Server.ConnectedClients.Count} clients");

                await Server.WriteAsync(Text).ConfigureAwait(false);
            }
            catch (Exception exception)
            {
                OnExceptionOccurred(exception);
            }
        }

        public async ValueTask DisposeAsync()
        {
            await Server.DisposeAsync().ConfigureAwait(false);
        }
    }

    public sealed partial class FormServer : Form
    {
        private string PipeName { get; }
        private PipeServer<string> Server { get; }
        private ISet<string> Clients { get; } = new HashSet<string>();

        public FormServer(string pipeName)
        {
            PipeName = "asdaskdjsa@岳雨婷as123131";

            InitializeComponent();

            Load += OnLoad;

            Server = new PipeServer<string>(PipeName);
            Server.ClientConnected += async (o, args) =>
            {
                Clients.Add(args.Connection.PipeName);
                UpdateClientList();

                AddLine($"{args.Connection.PipeName} connected!");

                try
                {
                    await args.Connection.WriteAsync("Welcome! You are now connected to the server.").ConfigureAwait(false);
                }
                catch (Exception exception)
                {
                    OnExceptionOccurred(exception);
                }
            };
            Server.ClientDisconnected += (o, args) =>
            {
                Clients.Remove(args.Connection.PipeName);
                UpdateClientList();

                AddLine($"{args.Connection.PipeName} disconnected!");
            };
            Server.MessageReceived += (o, args) => AddLine($"{args.Connection.PipeName}: {args.Message}");
            Server.ExceptionOccurred += (o, args) => OnExceptionOccurred(args.Exception);
        }

        private async void OnLoad(object sender, EventArgs eventArgs)
        {

            try
            {
                AddLine("Server starting...");

                await Server.StartAsync().ConfigureAwait(false);

                AddLine("Server is started!");
            }
            catch (Exception exception)
            {
                OnExceptionOccurred(exception);
            }
        }

        private void OnExceptionOccurred(Exception exception)
        {
            AddLine($"Exception: {exception}");
        }

        private void AddLine(string text)
        {
            richTextBoxMessages.Invoke(new Action(delegate
            {
                richTextBoxMessages.Text += $@"{text}{Environment.NewLine}";
            }));
        }

        private void UpdateClientList()
        {
            listBoxClients.Invoke(new Action(() =>
            {
                listBoxClients.Items.Clear();
                foreach (var client in Clients)
                {
                    listBoxClients.Items.Add(client);
                }
            }));
        }

        private async void ButtonSend_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(textBoxMessage.Text))
            {
                return;
            }

            try
            {
                AddLine($"Sent to {Server.ConnectedClients.Count} clients");

                await Server.WriteAsync(textBoxMessage.Text).ConfigureAwait(false);
            }
            catch (Exception exception)
            {
                OnExceptionOccurred(exception);
            }

            textBoxMessage.Invoke(new Action(delegate
            {
                textBoxMessage.Text = "";
            }));
        }

        public async ValueTask DisposeAsync()
        {
            await Server.DisposeAsync().ConfigureAwait(false);
        }
    }
}
